import React from 'react';
import style from './style.styl';
import cx from 'classnames';
import { Button,IconButton,Link,Avatar } from 'sq-ui';
import { Modal, MulSelect, Select, success, error,Tooltip, Checkbox} from '../../ui-components';
import ConverCell from './plugins/ConverCell';
import ConverTable from './plugins/ConverTable';
import util from '../../util';
const pageSize = 4;
const dateMap = [
    {
        value: '1',
        text: '每周',
        label: function (v) {return `每${v}`}
    },{
        value: '2',
        text: '每半月',
        label: function (v) {return `每个月第一个${v}，第三个${v}`}

    },{
        value: '3',
        text: '每月',
        label: function (v) {return `每个月第一个${v}`}

    },{
        value: '4',
        text: '不定期',
    },
]

const timeList = [
    {
        value: '1',
        text: '周一',
    },{
        value: '2',
        text: '周二'
    },{
        value: '3',
        text: '周三'
    },{
        value: '4',
        text: '周四'
    },{
        value: '5',
        text: '周五'
    },{
        value: '6',
        text: '周六'
    },{
        value: '7',
        text: '周日'
    },
]
class InitateConversation extends React.Component {
    static contextTypes = {
        router: React.PropTypes.object
    }
    constructor(props) {
        super(props);
        this.displayName = 'InitateConversation';
        this.state = {
            isShowAdd: false,
            editId: '',
            user: [],
            period: '2',
            time: '',
            isEdit: false,
            // autoSendEmail: 0, // 是否自动发送邮件
            msg: '',
        }
    }
    componentDidMount() {
        const pageNum = this.getPageNum(this.props);
        this.props.actions.fetchSchedule({
            pageNumber: pageNum,
            pageSize: pageSize
        });
    }
    componentWillUnmount() {
        this.props.actions.clearSchedule();
    }
    componentWillReceiveProps(nextProps) {
        const pageNum = this.getPageNum(this.props);
        const nextPageNum = this.getPageNum(nextProps);
        if(pageNum !== nextPageNum) {
            this.props.actions.fetchSchedule({
                pageNumber: nextPageNum,
                pageSize: pageSize
            });
        }
    }
    // 编辑 - 获取交谈周期
    getRemind = () => {
        const {
            period,
            time
        } = this.state;
        if(period !== '4'){ // 不为不定期时就去根据交谈周期去获取提醒时间
            this.props.actions.getRemind({
                periodType: period,
                remindDay: time,
            }, ({data}) => {
                this.setState({
                    msg: data,
                })
            });
        }else {
            this.setState({
                msg: '',
            })
        }
    }
    getPageNum = (props) => {
        const {
            pageNum = 1,
        } = props.location.query;
        return pageNum;
    }
    showAddModal = () => {
        this.setState({
            isShowAdd: true,
            user: [],
            period: '2',
            time: '1',
            isEdit: false,
            editId: '',
            // autoSendEmail: 0,
        },this.getRemind);
    }
    // 打开编辑对象弹窗时
    showEditModal = (v) => {
        this.setState({
            isShowAdd: true,
            user: [v.targetUserProfile],
            period: ''+ v.periodType,
            time: '' + v.remindDay,
            isEdit: !~v.remindDay,
            editId: v.convrScheduleId,
            // autoSendEmail: v.autoSendEmail,
        },this.getRemind);
    }
    handleUserSelect = (list) => {
        this.onFieldChange('user',list.length ? [list.pop()]:[])
    }
    onFieldChange = (key, value) => {
        this.setState({
            [key]: value,
        },this.getRemind);
    }
    editSuccess = (msg) => {
        success(msg || '更新成功');
        this.props.actions.fetchSchedule({
            pageNumber: this.getPageNum(this.props),
            pageSize: pageSize
        });
        this.setState({
            isShowAdd: false,
        })
    }
    // 提交新增/编辑的对象
    handleConverAdd = () => {
        const {
            user,
            period,
            time,
            editId,
            // autoSendEmail, // 是否自动发送邮件
        } = this.state;
        if(!user.length || (period !== '4' && (!time || time === '-1') )){
            return error('请填写完整');
        }else{
            if(editId) {
                this.props.actions.updateSchedule(editId, {
                    periodType: +period,
                    remindDay: period !== '4' ? (+time) : -1,
                    // autoSendEmail: period === '4' ? autoSendEmail : false // 是否自动发送邮件
                }, () => {
                    this.editSuccess();
                });
            }else{
                this.props.actions.addSchedule({
                    targetUserId: user[0].userId,
                    periodType: +period,
                    remindDay: period !== '4' ? (+time) : -1,
                    // autoSendEmail: period === '4' ? autoSendEmail : 0 // 是否自动发送邮件
                },() => {
                    this.editSuccess('添加成功');
                })
            }
        }
    }
    toggleActive = (id, flag) => {
        this.props.actions.updateSchedule(id, {
            isActive: flag,
        }, () => {
            this.editSuccess();
        });
    }
    fetchData = (i) => {
        this.context.router.push({
            pathname: '/conversation/initiate',
            query: {
                pageNum: i,
            }
        })
    }
    render() {
        const { atList } = this.props.app;
        let timeLabel = '请选择提醒时间';
        if(this.state.time){
            const labelFn = dateMap.find(v => v.value === (this.state.period||'1'));
            if(labelFn.label)
                timeLabel = labelFn.label(
                    (timeList.find(v => v.value === this.state.time)||{}).text
                );
        }
        const {
            schedules
        } = this.props.conversation;
        const pageNumber = this.getPageNum(this.props);
        const schedulesData = {
            pageNum: pageNumber,
            pageCount: 0,
            data: null,
        };
        if(schedules[`page_${pageNumber}`]){
            const dataItem = schedules[`page_${pageNumber}`];
            const {
                totalNumber = 0,
                convrScheduleVOs = [],
            } = dataItem || {};
            schedulesData.pageCount = Math.ceil(totalNumber/pageSize);
            schedulesData.data = convrScheduleVOs;
        }
        const {
            editId
        } = this.state;
        return (
            <div>
                <Button className={style['add-btn']} label={'添加交谈对象'} blue onClick={this.showAddModal}/>
                <ConverTable data={schedulesData} disabled={v => !v.isActive} fetchData={this.fetchData}>
                    <ConverCell item={v => v.targetUserProfile} header={'交谈对象'} width={150} render={v => {
                        return (
                            <Link
                                to={`/okr/objective-targetAll?userId=${v.userId}`}
                            >
                <span className={style['user-span']}>
                  <Avatar
                      src={v.avatarUrl}
                      style ={{
                          ...util.crop(v.avatarUrl,36)
                      }}
                      width={36}
                  />
                  <span>{v.fullName}</span>
                </span>
                            </Link>
                        );
                    }}/>
                    <ConverCell item={v => v['periodType']} header={'交谈周期'} width={100} render={(v) => {return (dateMap.find(i => i.value === ''+v)||{}).text}} />
                    <ConverCell item={v => v['convrCount']} header={'发起交谈次数'} width={120} />
                    <ConverCell item={v => v['lastConvrDate']} header={'上次发起时间'} width={150} render={v => !v ? '（尚未交谈）' : util.dateFormat(new Date(+v), 'yyyy-MM-dd')} />
                    <ConverCell item={v => v} header={'本周期是否已交谈'} width={250} render={v => {
                        const {
                            currentPeriodStatus,
                            isActive,
                            lastConvrDate,
                            periodType,
                        } = v;
                        let text, className;
                        if(periodType === 4){
                            text = '--';
                            className = 'normal';
                        }else if(!isActive){
                            text = '（已停止）';
                            className = 'normal';
                        }else if(currentPeriodStatus === 2){
                            text = '（对方已发起交谈）';
                            className = 'normal';
                        }else if(currentPeriodStatus === 1){
                            text = '已交谈';
                            className = 'success';
                        }else{
                            if(!v.lastConvrDate) text = '未交谈';
                            else text = `未交谈（距上次交谈${Math.ceil((Date.now() - lastConvrDate)/(24*60*60*1000))}天）`;
                            className = 'warning';
                        }
                        return <span className={style[`hehe_${className}`]}>{text}</span>;
                    }}/>
                    <ConverCell
                        render={v => {
                            return (
                                <div >
                                    <Tooltip tip={'停止交谈计划'} arrow={'top'} className={style['tip']}>
                                        <IconButton
                                            style={{ cursor: 'pointer',verticalAlign: 'middle'}}
                                            size="14"
                                            icon="lock"
                                            onClick={this.toggleActive.bind(this, v.convrScheduleId, 0)}
                                        />
                                    </Tooltip>
                                    <IconButton
                                        style={{ cursor: 'pointer',verticalAlign: 'middle'}}
                                        size="16"
                                        icon="edit"
                                        onClick={this.showEditModal.bind(this, v)}
                                    />
                                    <Link className={style['cell-link']} onClick={this.context.router.push.bind(this,{
                                        pathname:`/conversation/${v.convrScheduleId}/records`,
                                        state: {
                                            pageNum: this.getPageNum(this.props),
                                            user: v.targetUserProfile,
                                        }
                                    })} >查看历史</Link>
                                    <Button className={style['cell-btn']} style={{height: '30px',marginLeft:'10px'}} radius={'15px'} blueLine label={'新增记录'} onClick={this.context.router.push.bind(this,{
                                        pathname:`/conversation/${v.convrScheduleId}`,
                                        state: {
                                            pageNum: this.getPageNum(this.props),
                                            user: v.targetUserProfile,
                                        }
                                    })} />
                                </div>
                            );
                        }}
                        disabledRender={v => (
                            <Button className={style['cell-btn']} radius={'15px'} style={{marginTop:'5px',height: '30px'}} blueLine label={'恢复'} onClick={this.toggleActive.bind(this, v.convrScheduleId, 1)} />
                        )}
                    />
                </ConverTable>
                <Modal
                    active={this.state.isShowAdd}
                    onRequestClose={() => {this.setState({isShowAdd: false})}}
                    actions={['cancel', this.handleConverAdd ]}
                    title={`${editId ? '编辑' : '添加'}交谈对象`}
                >
                    <div className={style['add-modal']}>
                        <label>交谈对象</label>
                        {
                            editId ?
                                <Link
                                    to={``}
                                >
                <span className={style['user-span']}>
                  <Avatar
                      src={(this.state.user||[{}])[0].avatarUrl}
                      width={20}
                  />
                  <span>{(this.state.user||[{}])[0].fullName}</span>
                </span>
                                </Link>
                                :
                                <MulSelect
                                    placeholder="搜索交谈对象名称"
                                    value={[...this.state.user]}
                                    fetch={value => {
                                        if (value)
                                            this.props.actions.fetchAtList({
                                                keyword: value,
                                                type: 6
                                            });
                                        else
                                            this.props.actions.clearAtList();
                                    }}
                                    getItemAttrs={(item) => {
                                        return {
                                            label: item.fullName,
                                            img: item.avatarUrl,
                                        }
                                    }}
                                    onSelect={this.handleUserSelect}
                                    options={atList}
                                    excludeList={[...this.state.user,this.props.app.profile]}
                                />
                        }

                        <label>交谈周期</label>
                        <div className={style['date-select-box']}>
                            {
                                dateMap.map((v, i) => {
                                    return (
                                        <div key={i} className={cx({
                                            [style['date-select-item']]: true,
                                            [style['active']]: v.value === this.state.period,
                                        })} onClick={this.onFieldChange.bind(this, 'period', v.value)}>
                                            {v.text}
                                        </div>
                                    );
                                })
                            }
                        </div>
                        {
                            // 判断交谈周期是否为4
                            this.state.period !== '4' ?
                                <div>
                                    <label>提醒时间</label>
                                    {
                                        !this.state.time || this.state.time === '-1' || this.state.isEdit ?
                                            <div className={style['time-select-area']}>
                                                <Select
                                                    value={this.state.time}
                                                    onChange={(e) => {this.onFieldChange('time', e.target.value)}}
                                                    label={'期望周几提醒：'}
                                                    width={'200px'}
                                                >
                                                    <option value="">选择时间...</option>
                                                    {
                                                        (timeList || []).map((v, i) => (
                                                            <option key={i} value={v.value}>{ v.text }</option>
                                                        ))
                                                    }
                                                </Select>
                                                <Button disabled={!this.state.time} label={'确定'} style={{display: 'inline-block', height: '32px'}} blueLine onClick={()=> {this.setState({'isEdit': false})}} />
                                            </div>
                                            :
                                            <div className={style['period-label']}>
                                                <p>{timeLabel} </p>
                                                <IconButton
                                                    style={{ cursor: 'pointer'}}
                                                    size="16"
                                                    icon="edit"
                                                    onClick={() => {this.setState({isEdit: true})}}
                                                />
                                            </div>
                                    }
                                </div>
                                : null
                            /* <div>
                              <label>发送邮件</label>
                              <Checkbox
                                className={style['data-select-post']}
                                onClick={() => this.setState({ autoSendEmail: this.state.autoSendEmail === 0 ? 1 : 0 })}
                                active={this.state.autoSendEmail === 1}
                                label='自动发送'/>
                            </div> */
                        }
                        {
                            this.state.msg ?
                                <aside>对应日期的上午8:00，您会收到交谈提醒邮件。该交谈对象下次提醒日期为： {this.state.msg}</aside>
                                : null
                        }
                    </div>
                </Modal>
            </div>
        );
    }
}

export default InitateConversation;
